--package.path = '/usr/local/soft/openresty/lualib/resty/upload.lua;/usr/local/soft/openresty/lualib/resty/mysql.lua;'
--package.path = '/usr/local/soft/openresty/lualib/resty/upload.lua;/usr/local/soft/openresty/lualib/resty/mysql.lua;'
-- Author Jacky Peng
-- Date 2021/05/01
-- Version 1.5.0

--local upload = require "resty.upload"
local mysql = require "resty.mysql"
local template = require "resty.template"
local cjson = require "cjson"
--local chunk_size = 4096
--local form = upload:new(chunk_size)
--form:set_timeout(100000)

local mhost = '127.0.0.1'
local mport = 3306
local muser = 'lua'
local mpwd = 'lua123'
local mdb = 'files'

local function SQL()
	-- ALL Year Schedule
	local dt = os.date("%Y")
	local ll = 0
	print("\n.......SQL  dt:"..dt.."\n")
	local db,err = mysql:new()

	if not db then
		print("\n....SQL DB Init Error!\n")
		return nil,0
	end
	db:set_timeout(10000)

	local ok,err,errno,sqlstate = db:connect({
		host = mhost,
		port = mport,
		user = muser,
		password = mpwd,
		database = mdb
	})

	if not ok then
		ngx.say("\n....SQL sql ERROR: "..err..",////")
		return nil,0
	end

	local sql = nil
	sql = "select sys_name,sch_start,plantime,exestats from `t_schedule` where `sch_start` like '"..dt.."%'"
	--sql = "select sys_name,sch_start,plantime,exestats from `t_sch` where `sch_start` like '"..dt.."%'"
	--ngx.log(ngx.ERR,"SQL sql: ",sql)

	print("\n.....SQL sql: "..sql..'\n')
	local res,err,errno,sqlstate = db:query(sql)
	print("\n.....SQL res type: "..type(res).."\n")
	if not res then
		ngx.header["ID_Error"] = "sql_error"
		ngx.log(ngx.ERR, "\n----SQL not record.--------\n")
		return nil,0
	elseif #(res) > 0 then
		--local fname = res[1]["fname"]
		for i , row in ipairs(res) do 
			print("\n ------i :"..i..", Row type:"..type(row).."\n")
			print("\n .....row table. sys_name:"..row['sys_name']..", sch_start:"..row['sch_start']..", plantime:"..row['plantime']..", exestats:"..row['exestats'].."\n")
			ll = ll +1
		end
		ngx.log(ngx.ERR, "\n-----SQL ROWs:-----\n",ll,"\n")
		return res,ll
	else
		ngx.header["ID_Error"] = "sql other error"
		ngx.log(ngx.ERR,"\n------SQL ERROR----\n")
		return nil,0
	end
end

local function Data(rows)
	local s = 0
	local f = 0
	local p = 0
	local c = 0
	for i, row in ipairs(rows) do
		--if row['exestats'] == 'starting' then
		if row['exestats'] == '正在执行' then
			s = s + 1
		elseif row['exestats'] == '已完成' then
			f = f + 1
		elseif row['exestats'] == '等待中' then
			p = p + 1
		elseif row['exestats'] == '已取消' then
			c = c + 1
		else
			c = 0
		end
	end
	return s, f, p, c
end

local Y = os.date("%Y")
local M = os.date("%m")
local rows,lens = SQL()
print("\n++++++rows: "..type(rows)..", len: "..lens.."\n")
if not rows or lens == 0 then
	template.render("ss-error.html")
else
	local s,f,p,c = Data(rows)
	template.render("ss-all.html",{y=Y,total=lens,rows=rows,finished=f,prepare=p,cancel=c})
end
